package com.tyros.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

/**
 * @author zhangshuaiyin
 * @date 2022/1/15 22:37
 */
public class AESUtils {
    private static final String SHA_MODE = "SHA-256";
    private static final String AES_MODE = "AES/ECB/PKCS5Padding";

    private static SecretKeySpec initKey(String secret) {
        byte[] key;
        MessageDigest sha;
        SecretKeySpec secretKey;
        try {
            key = secret.getBytes(StandardCharsets.UTF_8);

            sha = MessageDigest.getInstance(SHA_MODE);

            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);

            secretKey = new SecretKeySpec(key, "AES");
            return secretKey;

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encrypt(String key, String rawData) {
        String encode = "";
        try {
            SecretKeySpec secretKey = AESUtils.initKey(key);
            Cipher cipher = Cipher.getInstance(AES_MODE);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            encode = Base64.getEncoder().encodeToString(cipher.doFinal(rawData.getBytes(StandardCharsets.UTF_8)));
            return encode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encode;
    }

    private static String decrypt(String key, String encode) {
        String message = "";
        try {
            SecretKeySpec secretKey = AESUtils.initKey(key);
            Cipher cipher = Cipher.getInstance(AES_MODE);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            message = new String(cipher.doFinal(Base64.getDecoder().decode(encode)));
            return message;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

    public static void main(String[] args) {
        final String message = "a0d71267251c4feb9e40799f47b2e71a|1|a0d71267251c4feb9e40799f47b2e71a";
        final String key = "channelSecret:a0d71267251c4feb9e40799f47b2e71a";
        final String key1 = "tyros";

        String enMessage = encrypt(key, message.trim());
        String enMessage1 = encrypt(key1, message.trim());
        String deMessage = decrypt(key, enMessage.trim());
        String deMessage1 = decrypt(key1, enMessage1.trim());

        System.out.println("加密密钥: " + key);
        System.out.println("加密前的内容: " + message);
        System.out.println("加密后的内容: " + enMessage);
        System.out.println("解密后的内容: " + deMessage);
        System.out.println("加密后的内容1: " + enMessage1);
        System.out.println("解密后的内容1: " + deMessage1);
    }

}
